package com.zb.service.impl;

import com.zb.exceptions.BusinessException;
import com.zb.service.LoginUserService;
import com.zb.util.JwtUtil;
import com.zb.util.ResultResponse;
import com.zb.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

@Service
public class LoginUserServiceImpl implements LoginUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Override
    public ResultResponse login(String nickname, String passwd) throws BusinessException {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(nickname,passwd);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        LoginUser loginUser =(LoginUser) authenticate.getPrincipal();
        if (loginUser == null) {
            return ResultResponse.error("没有查询到用户");
        }
        redisTemplate.boundValueOps("login:"+loginUser).set(loginUser);
        String token = JwtUtil.createJWT(loginUser.getUsername());

        return ResultResponse.success(token);
    }
}
